const nodemailer = require("nodemailer");
const Utils = require("../utils");

// 创建一个邮件客户端
const transporter = nodemailer.createTransport(Utils.getConfig().email);

class Email {
  /**
   * 发送邮件
   * @param {string} email 邮箱
   * @param {string} subject 主题
   * @param {string} html 内容
   * @returns {Promise<void>}
   */
  static send(email, subject, html) {
    return new Promise(async (resolve, reject) => {
      try {
        if (Email.isEmail(email) === false) {
          reject({ code: 400, message: "邮箱格式不正确" });
          return;
        }
        await transporter.sendMail({
          from: Utils.getConfig().email.auth.user,
          to: email,
          subject,
          html,
        });
        resolve();
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 判断邮箱格式是否正确
   * @param {string} email 邮箱
   * @returns {boolean}
   */
  static isEmail(email) {
    return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email);
  }
}

module.exports = Email;
